package com;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

public class ServerThread implements Runnable{
	private ServerSocket server;
	private Socket socket;
	private MainFrame mf;
	private ObjectInputStream ois;
	public ServerThread(MainFrame mainFrame) {
		mf=mainFrame;
		try {
			server=new ServerSocket(9988);
			mf.port=9988;
		} catch (IOException e) {
			try {
				server=new ServerSocket(9989);
				mf.port=9989;
			} catch (IOException e1) {
				System.out.println("服务器创建失败");
			}
		}
	}
	@Override
	public void run() {
		while(true){
			try {
				socket=server.accept();
				if(mf.isLinked){
					mf.send(socket, LoginPanel.HAVEOPPONENT);
					continue;
				}
				ois=new ObjectInputStream(socket.getInputStream());
				Object message=ois.readObject();
				if(message instanceof User){
					User user=(User) message;
					int f=JOptionPane.showConfirmDialog(null, 
							user.getName()+"请求跟您联机，是否同意？", "信息提示", 
							JOptionPane.YES_NO_OPTION);
					if(f==JOptionPane.YES_OPTION)
					{
					  LoginPanel loginPanel=(LoginPanel) mf.getRootPane().getGlassPane();
					  loginPanel.tf[1].setText(socket.getInetAddress().getHostAddress());
					  loginPanel.tf[1].setEnabled(false);
					  user.setOpponent(true);
					  mf.setSocket(socket);
					  mf.send(socket,LoginPanel.AGREE);
					  mf.setUser(user);
					  if(mf.user!=null) mf.send(socket, mf.user);
					  mf.isLinked=true;
					}
					else{
						mf.send(socket,LoginPanel.REFUSE);
						socket.close();
						mf.setSocket(null);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}
